package pkg

import (
	"bytes"
	"encoding/json"
	"ginWork/global"
	"ginWork/types"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"io/ioutil"
	"log"
	"net/http"
	"os"
)

func init() {
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold:             0,             // Slow SQL threshold
			LogLevel:                  logger.Silent, // Log level
			IgnoreRecordNotFoundError: true,          // Ignore ErrRecordNotFound error for logger
			ParameterizedQueries:      true,          // Don't include params in the SQL log
			Colorful:                  false,         // Disable color
		},
	)

	dsn := "root:123456@tcp(127.0.0.1:3306)/week?charset=utf8mb4&parseTime=True&loc=Local"

	global.Db, _ = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
	})

}

func EsAdd() {

	var goods types.Goods

	marshal, err := json.Marshal(goods)
	if err != nil {
		return
	}

	request, err := http.NewRequest("POST", "http://113.44.72.167:9200/"+"goods/"+"_doc", bytes.NewBuffer(marshal))
	if err != nil {
		return
	}

	request.Header.Set("Content-Type", "application/json")

	client := &http.Client{}

	response, err := client.Do(request)
	if err != nil {
		return
	}

	defer response.Body.Close()

	responseBody, err := ioutil.ReadAll(response.Body)

	if err != nil {
		return
	}

	json.Unmarshal(responseBody, &goods)
}

func EsSearch() {

	var goods types.Goods

	marshal, err := json.Marshal(goods)
	if err != nil {
		return
	}

	request, err := http.NewRequest("POST", "http://113.44.72.167:9200/"+"goods/"+"_search", bytes.NewBuffer(marshal))
	if err != nil {
		return
	}

	request.Header.Set("Content-Type", "application/json")

	client := &http.Client{}

	response, err := client.Do(request)
	if err != nil {
		return
	}

	defer response.Body.Close()

	responseBody, err := ioutil.ReadAll(response.Body)

	if err != nil {
		return
	}

	json.Unmarshal(responseBody, &goods)
}
